# coding=utf-8
"""
    Flask 环境配置, dev, test, prod
"""
import os
from typing import Dict, Type
import pymysql
from dbutils.pooled_db import PooledDB

from utils.path_util import LOG_PATH


# @Time    :  2024-10-16 17:28:09
# @Author  :  jiangtong
# @Email   :  gingerqgyy@outlook.com
# @Project :  ginger_yl_test_boost
# @File    :  config.py


# Config 父类 : ( 属性其实是 Dev 的属性 )
class Config:
    # 密钥 :
    SECRET_KEY = 'GINGER_TEST_BOOST'
    JWT_ALGORITHM = 'HS256'
    JWT_EXPIRATION_HOURS = 2
    JWT_EXPIRATION_DAYS = 7
    JWT_REFRESH_DAYS = 30

    # 日志相关 :
    DEBUG: True
    TESTING = True
    LOG_LEVEL = 'INFO'
    LOG_FILE = os.path.join(LOG_PATH, 'app.log')

    # 默认数据库连接信息 (子类覆盖) :
    DB_HOST = '192.168.3.70'
    DB_PORT = 3306
    DB_USER = 'root'
    DB_PASSWORD = 'y123456'
    DB_NAME = 'test'

    # 连接池配置, 子类如无特殊设计, 无需定义, 直接继承
    POOL_MIN_CONN = 1
    POOL_MAX_CONN = 20

    # 初始化 app , 子类覆盖 :
    def init_app(self, app):
        """ 初始化环境 """
        app.db_pool = self.get_db_pool()

        # 测试数据库连接
        with app.db_pool.connection() as conn:
            with conn.cursor() as cursor:
                cursor.execute('SELECT COUNT(*) FROM test.users;')
                result = cursor.fetchone()
                app.logger.info(f'Database connection successful, Select users count successful, users count: {result[0]}')
            app.logger.info(f'Connected to database')
        app.logger.info('Environment initialized')

    # 数据库连接池, 子类覆盖 :
    @staticmethod
    def get_db_pool():
        """ 创建连接池 """
        return PooledDB(
            # 使用 pymysql 作为数据库驱动
            creator=pymysql,
            mincached=Config.POOL_MIN_CONN,
            maxcached=Config.POOL_MAX_CONN,
            host=Config.DB_HOST,
            port=Config.DB_PORT,
            user=Config.DB_USER,
            password=Config.DB_PASSWORD,
            # database=Config.DB_NAME,
            charset='utf8mb4',
        )


# 开发环境 :
class DevelopmentConfig(Config):
    # 密钥 :
    SECRET_KEY = 'dev_secret_key'

    # 日志相关 :
    LOG_LEVEL = 'DEBUG'

    # 数据库相关 :
    DB_HOST = '192.168.3.70'
    DB_PORT = 3306
    DB_USER = 'root'
    DB_PASSWORD = 'y123456'
    DB_NAME = 'test'

    def init_app(self, app):
        """ 初始化开发环境 """
        super().init_app(app)
        # 环境额外配置 : 详细开发日志, 内置调试工具, 允许跨域, 禁用一些安全机制等;


# 测试环境 :
class TestConfig(Config):
    # 密钥 :
    SECRET_KEY = 'test_secret_key'

    # 日志相关 :
    LOG_LEVEL = 'DEBUG'

    # 数据库相关 :
    DB_HOST = '192.168.3.70'
    DB_PORT = 3306
    DB_USER = 'root'
    DB_PASSWORD = 'y123456'
    DB_NAME = 'test'

    def init_app(self, app):
        """ 初始化测试环境 """
        super().init_app(app)
        # 环境额外配置 : 比如单元测试, 连接第三方测试服务等;


# 生产环境 :
class ProductionConfig(Config):
    # 密钥 :
    SECRET_KEY = 'prod_secret_key'

    DEBUG = False
    LOG_LEVEL = 'INFO'
    LOG_FILE = os.path.join(LOG_PATH, 'app_product.log')

    DB_HOST = 'prod-db-server'
    DB_PORT = 3306
    DB_USER = 'prod_user'
    DB_PASSWORD = 'prod_password'
    DB_NAME = 'prod_db'

    def init_app(self, app):
        """ 初始化生产环境 """
        super().init_app(app)
        # 环境额外配置 : 比如性能监控, 严格的安全设置, 启用 Https, CSRF 保护, 连接实际第三方服务等;


conf: Dict[str, Type[Config]] = {
    'dev': DevelopmentConfig,
    'test': TestConfig,
    'prod': ProductionConfig,
    'default': DevelopmentConfig,
}
